package com.hmys.api.controller;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.ValidSMSResult;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.DateUtil;
import com.github.pagehelper.PageInfo;
import com.hmys.api.config.Constant;
import com.hmys.api.config.SMSConfig;
import com.hmys.api.model.*;
import com.hmys.api.response.Result;
import com.hmys.api.response.ResultCode;
import com.hmys.api.response.ResultPage;
import com.hmys.api.service.*;
import com.hmys.api.utils.DateUtils;
import com.hmys.api.utils.OSSUtil;
import com.hmys.api.utils.ValidationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;

/**
 * Created by chen365 on 2018/03/14.
 */
@RestController
@Api(tags = "用户")
public class UserController {

    @Autowired
    private WebUserService webUserService;
    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private LoginPersistenceService loginPersistenceService;
    @Autowired
    private SMSConfig smsConfig;
    @Autowired
    private UploadService uploadService;

    @Autowired
    private WebHouseService webHouseService;

    @ApiOperation(value = "登陆", notes = "登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", required = true, paramType = "query")
    })
    @PostMapping(value = "/login")
    public Object login(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam("phone") String phone,
                        @RequestParam("msg") String msg,
                        @RequestParam("msgId") String msgId) {

        if (!ValidationUtil.isPhone(phone)) {
            return new Result(ResultCode.ERROR_PHONE);
        }

//        if (StringUtils.isEmpty(msg)) {
//            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);
//        }
//
//        if (StringUtils.isEmpty(msgId)) {
//            return new Result(ResultCode.EMPTY_MSG_ID);
//        }

        WebUser bUser = webUserService.selectByPhone(phone);
        if (bUser == null) {
            return new Result(ResultCode.NOT_EXIST_USER);
        }

        UserDetails userDetails = authenticationService.loadUserByPhone(phone);

        /*
        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
            if (!result.getIsValid()) {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (APIRequestException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.ERROR);
        }

        */

        Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, msg, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);

        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
            @Override
            public String getParameter(String name) {
                return "true";
            }
        };

        PersistentTokenBasedRememberMeServices tokenService = new PersistentTokenBasedRememberMeServices(msg, authenticationService, loginPersistenceService);
        tokenService.loginSuccess(wrapper, response, auth);

        Principal principal = (Principal) userDetails;
        WebUser user = principal.getUser();

        return new Result(ResultCode.SUCCESS, user);
    }

    /**
     * 退出登陆
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "退出登陆", notes = "退出登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/exit")
    public Object exit(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        new SecurityContextLogoutHandler().logout(request, response, auth);
        Arrays.stream(request.getCookies()).forEach(cookie -> {
            if (cookie.getName().equalsIgnoreCase("remember-me")) {
                cookie.setMaxAge(0);
                cookie.setValue(null);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        });
        return new Result(ResultCode.SUCCESS);
    }

    @ApiOperation(value = "客户注册", notes = "客户注册", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信Id", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "name", value = "名字", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "email", value = "邮箱", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "weiXin", value = "微信号", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "qq", value = "QQ", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "investmentObjective", value = "投资目的", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "capitalSource", value = "资金来源，国内资金，海外资金", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyRoom", value = "房型倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySite", value = "地点倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyPrice", value = "价格倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySize", value = "面积倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySchool", value = "学校倾向(幼儿园,小学,初中,高中,大学)", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "province", value = "省", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "city", value = "市", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "area", value = "区", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "address", value = "详细地址", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "Date", name = "birthDate", value = "生日", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "marital", value = "婚姻，0保密，1已婚，2未婚，3离异", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "income", value = "年收入", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobTitle", value = "职称", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobType", value = "工作行业", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "sex", value = "性别，0女，1男", required = false, paramType = "query")
    })
    @PostMapping(value = "/register")
    public Object register(String msg, String msgId, String name, String email, String phone,
                           String weiXin, String qq, String investmentObjective, String capitalSource, String tendencyRoom,
                           String tendencySite, String tendencyPrice, String tendencySize, String tendencySchool, String province, String city,
                           String area, String address, Date birthDate, Integer marital, String income, String jobTitle,
                           String jobType, Integer sex) {

        if (StringUtils.isEmpty(name))
            return new Result(ResultCode.EMPTY_NAME);

        if (!StringUtils.isEmpty(email)) {
            if (!ValidationUtil.isEmail(email))
                return new Result(ResultCode.ERROR_EMAIL);
        }
        if (!ValidationUtil.isPhone(phone))
            return new Result(ResultCode.ERROR_PHONE);


        if (StringUtils.isEmpty(msg))
            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);

        if (StringUtils.isEmpty(msgId))
            return new Result(ResultCode.EMPTY_MSG_ID);


        if (webUserService.isExist(phone)) {
            return new Result(ResultCode.PHONE_REGISTERED);
        }

        WebUser webUser = new WebUser();

        webUser.setPhone(phone);
        webUser.setName(name);
        webUser.setEmail(email);

        if (!StringUtils.isEmpty(weiXin)) {
            webUser.setWeixin(weiXin);
        }
        if (!StringUtils.isEmpty(qq)) {
            webUser.setQq(qq);
        }
        if (!StringUtils.isEmpty(investmentObjective)) {
            webUser.setInvestmentObjective(investmentObjective);
        }
        if (!StringUtils.isEmpty(capitalSource)) {
            webUser.setCapitalSource(capitalSource);
        }
        if (!StringUtils.isEmpty(tendencyRoom)) {
            webUser.setTendencyRoom(tendencyRoom);
        }
        if (!StringUtils.isEmpty(tendencySite)) {
            webUser.setTendencySite(tendencySite);
        }
        if (!StringUtils.isEmpty(tendencyPrice)) {
            webUser.setTendencyPrice(tendencyPrice);
        }
        if (!StringUtils.isEmpty(tendencySize)) {
            webUser.setTendencySize(tendencySize);
        }
        if (!StringUtils.isEmpty(tendencySchool)) {
            webUser.setTendencySchool(tendencySchool);
        }
        if (!StringUtils.isEmpty(province)) {
            webUser.setProvince(province);
        }
        if (!StringUtils.isEmpty(city)) {
            webUser.setCity(city);
        }
        if (!StringUtils.isEmpty(area)) {
            webUser.setArea(area);
        }
        if (!StringUtils.isEmpty(address)) {
            webUser.setAddress(address);
        }
        if (!StringUtils.isEmpty(birthDate)) {
            webUser.setBirthdate(birthDate);
        }
        if (!StringUtils.isEmpty(marital)) {
            webUser.setMarital(marital);
        }
        if (!StringUtils.isEmpty(income)) {
            webUser.setIncome(income);
        }
        if (!StringUtils.isEmpty(jobTitle)) {
            webUser.setJobTitle(jobTitle);
        }
        if (!StringUtils.isEmpty(jobType)) {
            webUser.setJobType(jobType);
        }
        if (!StringUtils.isEmpty(sex)) {
            webUser.setSex(sex);
        }

        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
            if (result.getIsValid()) {
                if (webUserService.create(webUser) == 1) {
                    return new Result(ResultCode.SUCCESS);
                }
            } else {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e1) {
            e1.printStackTrace();
        } catch (APIRequestException e1) {
            e1.printStackTrace();
        }
        return new Result(ResultCode.FAIL);
    }


    @ApiOperation(value = "客户注册(简明)", notes = "客户注册(简明)", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信Id", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "name", value = "名字", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "email", value = "邮箱", required = false, paramType = "query")
    })
    @PostMapping(value = "/signUp")
    public Object signUp(HttpServletRequest request, HttpServletResponse response, String msg, String msgId, String name, String email, String phone) {

        if (StringUtils.isEmpty(name))
            return new Result(ResultCode.EMPTY_NAME);

        if (!StringUtils.isEmpty(email)) {
            if (!ValidationUtil.isEmail(email))
                return new Result(ResultCode.ERROR_EMAIL);
        }
        if (!ValidationUtil.isPhone(phone))
            return new Result(ResultCode.ERROR_PHONE);

        if (StringUtils.isEmpty(msg))
            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);

        if (StringUtils.isEmpty(msgId))
            return new Result(ResultCode.EMPTY_MSG_ID);

        if (webUserService.isExist(phone)) {
            return new Result(ResultCode.PHONE_REGISTERED);
        }

        WebUser webUser = new WebUser();

        webUser.setPhone(phone);
        webUser.setName(name);
        webUser.setEmail(email);

        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
            if (result.getIsValid()) {
                WebUser entity = webUserService.sginUp(webUser);
                if (entity.getUserId() != null && entity.getUserId() > 0) {

                    UserDetails userDetails = authenticationService.loadUserByPhone(entity.getPhone());

                    Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, msg, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(auth);

                    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                        @Override
                        public String getParameter(String name) {
                            return "true";
                        }
                    };

                    PersistentTokenBasedRememberMeServices tokenService = new PersistentTokenBasedRememberMeServices(msg, authenticationService, loginPersistenceService);
                    tokenService.loginSuccess(wrapper, response, auth);

                    Principal principal = (Principal) userDetails;
                    WebUser user = principal.getUser();

                    return new Result(ResultCode.SUCCESS, user);
                }
            } else {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e1) {
            e1.printStackTrace();
        } catch (APIRequestException e1) {
            e1.printStackTrace();
        }
        return new Result(ResultCode.FAIL);
    }

    @ApiOperation(value = "用户基础信息", notes = "用户基础信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/user/basics/info")
    public Object basicsInfo() {
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }
        WebUserBasics webUserBasics = webUserService.selectBasicsByPrimaryKey(webUser.getUserId());
        return new Result(ResultCode.SUCCESS, webUserBasics);
    }


    @ApiOperation(value = "用户投资信息", notes = "用户投资信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/user/invest/info")
    public Object investInfo() {
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }
        WebUserInvest webUserInvest = webUserService.selectInvestByPrimaryKey(webUser.getUserId());
        return new Result(ResultCode.SUCCESS, webUserInvest);
    }

    @ApiOperation(value = "修改用户基础信息", notes = "修改用户基础信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "name", value = "名字", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "email", value = "邮箱", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "weiXin", value = "微信号", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "qq", value = "QQ", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "province", value = "省", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "city", value = "市", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "area", value = "区", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "address", value = "详细地址", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "birthDate", value = "生日", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "marital", value = "婚姻，0保密，1已婚，2未婚，3离异", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "income", value = "年收入", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobTitle", value = "职称", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobType", value = "工作行业", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "sex", value = "性别，0女，1男", required = false, paramType = "query")
    })
    @PostMapping(value = "/user/basics/update")
    public Object basics(String name, String weiXin, String qq, String province, String city, String area,
                         String address, String birthDate, Integer marital, String income, String jobTitle,
                         String jobType, Integer sex, String email) {
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }
        if (StringUtils.isEmpty(name)) {
            return new Result(ResultCode.EMPTY_NAME);
        }
        WebUserBasics webUserBasics = new WebUserBasics();
        webUserBasics.setName(name);
        webUserBasics.setWeixin(weiXin);
        webUserBasics.setQq(qq);
        webUserBasics.setProvince(province);
        webUserBasics.setCity(city);
        webUserBasics.setArea(area);
        webUserBasics.setAddress(address);
        Date d = null;
        try {
            d = DateUtils.parseDate(birthDate, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        webUserBasics.setBirthdate(d);
        webUserBasics.setMarital(marital);
        webUserBasics.setIncome(income);
        webUserBasics.setJobTitle(jobTitle);
        webUserBasics.setJobType(jobType);
        webUserBasics.setSex(sex);
        webUserBasics.setEmail(email);
        webUserBasics.setUserId(webUser.getUserId());
        if (webUserService.updateBasicsByPrimaryKey(webUserBasics) > 0) {
            return new Result(ResultCode.SUCCESS);
        }

        return new Result(ResultCode.FAIL);
    }

    @ApiOperation(value = "修改投资偏好", notes = "修改投资偏好", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "investmentObjective", value = "投资目的", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "capitalSource", value = "资金来源，国内资金，海外资金", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyRoom", value = "房型倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySite", value = "地点倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyPrice", value = "价格倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySize", value = "面积倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySchool", value = "学校倾向(幼儿园,小学,初中,高中,大学)", required = false, paramType = "query")
    })
    @PostMapping(value = "/user/invest/update")
    public Object invest(String investmentObjective, String capitalSource, String tendencyRoom, String tendencySite,
                         String tendencyPrice, String tendencySize, String tendencySchool
    ) {
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }
        WebUserInvest webUserInvest = new WebUserInvest();

        if (!StringUtils.isEmpty(investmentObjective)) {
            webUserInvest.setInvestmentObjective(investmentObjective);
        }
        if (!StringUtils.isEmpty(capitalSource)) {
            webUserInvest.setCapitalSource(capitalSource);
        }
        if (!StringUtils.isEmpty(tendencyRoom)) {
            webUserInvest.setTendencyRoom(tendencyRoom);
        }
        if (!StringUtils.isEmpty(tendencySite)) {
            webUserInvest.setTendencySite(tendencySite);
        }
        if (!StringUtils.isEmpty(tendencyPrice)) {
            webUserInvest.setTendencyPrice(tendencyPrice);
        }
        if (!StringUtils.isEmpty(tendencySize)) {
            webUserInvest.setTendencySize(tendencySize);
        }
        if (!StringUtils.isEmpty(tendencySchool)) {
            webUserInvest.setTendencySchool(tendencySchool);
        }
        webUserInvest.setUserId(webUser.getUserId());
        if (webUserService.updateInvestByPrimaryKey(webUserInvest) > 0) {
            return new Result(ResultCode.SUCCESS);
        }

        return new Result(ResultCode.FAIL);
    }


    /*
    @ApiOperation(value = "上传头像", notes = "上传头像", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/upload/photo")
    public Object uploadPhoto(MultipartFile myFile) {

        WebUser webUser = webUserService.getCurrentUser();
        System.err.println(webUser.toString());
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }

        try {
            if (!myFile.isEmpty()) {
                String originalFileName = myFile.getOriginalFilename();
                String ext = FilenameUtils.getExtension(originalFileName);
                String filename = UUID.randomUUID().toString() + "." + ext;
                String uploadPath = Constant.PIC_LOCATION;
                File file = new File(uploadPath, filename);
                FileUtils.copyInputStreamToFile(myFile.getInputStream(), file);

                String imageUrl = uploadService.upload(file, "user");
                if (!StringUtils.isEmpty(imageUrl)) {
                    WebUser record = new WebUser();
                    record.setUserId(webUser.getUserId());
                    record.setPhoto(imageUrl);
                    webUserService.updatePhotoByPrimaryKey(record);
                    return new Result(ResultCode.SUCCESS, imageUrl);
                }
            } else {
                return new Result(ResultCode.EMPTY_PHOTO);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(ResultCode.FAIL);
    }

    */

    @ApiOperation(value = "上传单图", notes = "上传单图", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/upload/photo")
    public Object singleUpload(@RequestParam("myFile") MultipartFile myFile) {
        try {
            if (!myFile.isEmpty()) {
                String originalFileName = myFile.getOriginalFilename();
                String ext = FilenameUtils.getExtension(originalFileName);
                String filename = UUID.randomUUID().toString() + "." + ext;
                String uploadPath = Constant.PIC_LOCATION;
                File file = new File(uploadPath, filename);
                FileUtils.copyInputStreamToFile(myFile.getInputStream(), file);

                String imageUrl = uploadService.upload(file, "user");
                return new Result(ResultCode.SUCCESS, imageUrl);
            } else {
                return new Result(ResultCode.EMPTY_PHOTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(ResultCode.FAIL);
    }

    @ApiOperation(value = "修改头像", notes = "修改头像", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/update/photo")
    public Object updatePhoto(String photo) {
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }
        WebUser record = new WebUser();
        record.setUserId(webUser.getUserId());
        record.setPhoto(photo);
        if (webUserService.updatePhotoByPrimaryKey(record) > 0) {
            return new Result(ResultCode.SUCCESS);
        }
        return new Result(ResultCode.FAIL);
    }


    @ApiOperation(value = "上传头像", notes = "上传头像", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "pic", value = "base64", required = true, paramType = "query")
    })
    @PostMapping(value = "/photo/upload")
    public Object photoUpload(@RequestParam("pic") String pic) {
        try {
            pic = URLDecoder.decode(pic, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return new Result(ResultCode.ERROR_UPLOAD);
        }
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser == null) {
            return new Result(ResultCode.USER_IS_NOT_LOGIN);
        }
        try {
            String photo = uploadService.upload(pic);
            if (!StringUtils.isEmpty(photo)) {
                WebUser record = new WebUser();
                record.setUserId(webUser.getUserId());
                record.setPhoto(photo);
                webUserService.updatePhotoByPrimaryKey(record);
                return new Result(ResultCode.SUCCESS, photo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL, e.getMessage());
        }
        return new Result(ResultCode.FAIL);
    }


}
